import { 
  AmbientLight,
  Group,
  PerspectiveCamera, 
  Scene, 
  SpotLight, 
  Sprite, 
  SpriteMaterial, 
  WebGLRenderer
} from "three"
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls'
import stats from "../../utils/stats"
import { GUI } from 'dat.gui'

const scene = new Scene()
const camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000)
camera.position.set(-20, 12, 200)
camera.lookAt(0, 0, 0)

const renderer = new WebGLRenderer({ antialias: true })
renderer.setClearColor(0x000000)
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

const controls = {
  animate: true
}

let group = new Group()

for (let x = -15; x < 15; x++) {
  for (let y = -15; y < 15; y++) {
    let material = new SpriteMaterial({
      color: Math.random() * 0xffffff,
    })
    let sprite = new Sprite(material)
    sprite.position.set(x * 4, y * 4, 0)
    group.add(sprite)
  }
}

scene.add(group)

const ambient = new AmbientLight(0x0c0c0c)
scene.add(ambient)

const spotlight = new SpotLight(0xffffff)
spotlight.position.set(100, 100, 100)
scene.add(spotlight)
// scene.add(new SpotLightHelper(spotlight))

const gui = new GUI()
gui.add(controls, 'animate')

const trackballControls = new TrackballControls(camera, renderer.domElement)

function render() {
  stats.update()
  trackballControls.update()

  if (controls.animate) {
    group.rotation.y += 0.01
    group.rotation.x += 0.01
  }

  requestAnimationFrame(render)
  renderer.render(scene, camera)
}
render()